/*
 * LoopThread.cpp
 *
 *  Created on: 2020年9月17日
 *      Author: chuanjiang.zh
 */

#include "LoopThread.h"


LoopThread::LoopThread()
{
}

LoopThread::~LoopThread()
{
}

void LoopThread::post(Task task)
{
	{
		std::lock_guard< std::mutex >	lock(m_mutex);
		m_taskQueue.push_back(task);
	}

	m_eventTask.post();
}

void LoopThread::clearTask()
{
	{
		std::lock_guard< std::mutex >	lock(m_mutex);
		m_taskQueue.clear();
	}

	m_eventTask.post();
}

void LoopThread::onIdle()
{
	int ms = IDLE_DURATION;
	m_eventTask.timedwait(ms);
}

int LoopThread::run()
{
	while (!m_canExit)
	{
		if (!fetchAndHandle())
		{
			onIdle();
		}
	}
	return 0;
}

void LoopThread::doStop()
{
	m_eventTask.post();
}


bool LoopThread::fetchAndHandle()
{
	Task task;
	if (!fetchTask(task))
	{
		return false;
	}

	task();

	return true;
}

bool LoopThread::fetchTask(Task& task)
{
	bool got = false;
	std::lock_guard< std::mutex >	lock(m_mutex);
	if (m_taskQueue.size() > 0)
	{
		task = m_taskQueue.front();
		m_taskQueue.pop_front();
		got = true;
	}
	return got;
}
